﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace RM.BasicLibrary.Transfers.Https
{
    public interface IHttp
    {
        /// <summary>
        /// 请求成功调用的方法
        /// </summary>
        Action<HttpStatusCode, string> OnComplete { get; set; }
        /// <summary>
        /// 请求的类型
        /// </summary>
        string ContentType { get; set; }
        /// <summary>
        /// request 带全部参数的请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="param"></param>
        /// <param name="method"></param>
        /// <returns></returns>
        string Request(string url, string param = null, string method = "POST");
        /// <summary>
        /// POST 带参数的请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        string Post(string url, string param);
        /// <summary>
        /// 返回指定的实体带参数的请求
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        T Post<T>(string url, string param);
        /// <summary>
        /// 获取Get请求
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        string Get(string url);
        /// <summary>
        /// 返回指定实体的带参数的请求
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url"></param>
        /// <returns></returns>
        T Get<T>(string url);
    }
    /// <summary>
    /// Http请求
    /// </summary>
    public class Http : IHttp
    {
        public const string POST = "POST";
        public const string GET = "GET";
        public const string ContentTypeJson = "application/json";

        /// <summary>
        /// 请求成功调用的方法
        /// </summary>
        public Action<HttpStatusCode, string> OnComplete { get; set; }
        public string ContentType { get; set; } = "application/x-www-form-urlencoded";

        /// <summary>
        ///通用HttpWebRequest
        /// </summary>
        /// <param name="method">请求方式（POST/GET）</param>
        /// <param name="url">请求地址</param>
        /// <param name="param">请求参数</param>
        /// <param name="onComplete">完成后执行的操作(可选参数，通过此方法可以获取到HTTP状态码)</param>
        /// <returns>请求返回的结果</returns>
        public string Request(string url, string param = null, string method = POST)
        {

            url.NotNull();
            switch (method.ToUpper())
            {
                case POST:
                    return Post(url, param);
                case GET:
                    return Get(url);
                default:
                    return Get(url);
            }
        }

        /// <summary>
        /// Post请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="param">参数</param>
        /// <param name="onComplete">完成后执行的操作(可选参数，通过此方法可以获取到HTTP状态码)</param>
        /// <returns>请求返回的结果</returns>
        public string Post(string url, string param)
        {
            url.NotNull();
            UrlCheck(ref url);
            byte[] bufferBytes = Encoding.UTF8.GetBytes(param);
            var request = WebRequest.Create(url) as HttpWebRequest;
            request.Method = POST;
            request.ContentLength = bufferBytes.Length;
            request.ContentType = ContentType;
            Root.BasicIns.ExFilter.Execute(() =>
            {
                using (var requestStream = request.GetRequestStream())
                {
                    requestStream.Write(bufferBytes, 0, bufferBytes.Length);
                }
            }, "POST request failed");
            return HttpRequest(request);
        }
        /// <summary>
        /// Post请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="param">参数</param>
        /// <param name="onComplete">完成后执行的操作(可选参数，通过此方法可以获取到HTTP状态码)</param>
        /// <returns>请求返回的结果</returns>
        public T Post<T>(string url, string param)
        {
            return Root.BasicIns.JsonSerialize.Deserialize<T>(Post(url, param));
        }
        /// <summary>
        /// GET请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="param">参数</param>
        /// <param name="onComplete">完成后执行的操作(可选参数，通过此方法可以获取到HTTP状态码)</param>
        /// <returns>请求返回结果</returns>
        public string Get(string url)
        {
            UrlCheck(ref url);
            var request = WebRequest.Create(url) as HttpWebRequest;
            request.Method = GET;
            request.ContentType = ContentType;
            return HttpRequest(request);
        }
        /// <summary>
        /// GET请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="param">参数</param>
        /// <param name="onComplete">完成后执行的操作(可选参数，通过此方法可以获取到HTTP状态码)</param>
        /// <returns>请求返回结果</returns>
        public T Get<T>(string url)
        {
            return Root.BasicIns.JsonSerialize.Deserialize<T>(Get(url));
        }

        /// <summary>
        /// 请求的主体部分（由此完成请求并返回请求结果）
        /// </summary>
        /// <param name="request">请求的对象</param>
        /// <param name="onComplete">完成后执行的操作(可选参数，通过此方法可以获取到HTTP状态码)</param>
        /// <returns>请求返回结果</returns>
        private string HttpRequest(HttpWebRequest request)
        {
            string result = string.Empty;
            HttpWebResponse response = null;
            Root.BasicIns.ExFilter.Execute(() =>
            {
                response = request.GetResponse() as HttpWebResponse;
                using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                    result = reader.ReadToEnd();
                OnComplete?.Invoke(HttpStatusCode.NotFound, result);
            });
            return result;
        }

        /// <summary>
        /// URL拼写完整性检查
        /// </summary>
        /// <param name="url">待检查的URL</param>
        private void UrlCheck(ref string url)
        {
            if (!url.StartsWith("http://") && !url.StartsWith("https://"))
                url = "http://" + url;
        }
    }
}
